'''
Created on Aug 13, 2012

This script starts the application, and links/fills all relevant objects.
In contrast to run it can show the pylab-figures (if configured in the 
config-file with show_pylab).

@author: petrina
'''

from error.log_manager import Log_manager
from processing.processor import Processor
from output.outputmanager import Output_manager
from processing.link_indicatorset import Link_indicatorset
from processing.network_indicatorset import Network_indicatorset
from input.database_input import Database_input
from configuration.config import Config
import pylab
import sys
import os
import logging

# Store current working directory
pwd = os.path.dirname(os.path.realpath(__file__))

# Append current directory to the python path
sys.path.append(pwd)

# get path for the configfile, loglevel and logfile from the process' parameters
# First passed parameter: Configuration file path
cfgfile = str(sys.argv[1]).strip() if len(sys.argv) > 1 else 'configuration/user_config_pp.ini'

logfile = None
# Second passed parameter: loglevel as integer value
if len(sys.argv) > 2: 
    # possible log levels (CRITICAL=50, ERROR=40, WARNING=30, INFO=20, DEBUG=10, not set = 0)
    try:
        loglevel = int(sys.argv[2].strip())
    except:
        # no numeric value given - use standard log level
        print sys.argv[2], " is an invalid loglevel! Using standard loglevel instead"

# Third passed parameter: file path for the logfile
loglevel = str(sys.argv[3]).strip() if len(sys.argv) > 3 else None
    
# init logging    
Log_manager(loglevel, logfile)
    
configparser = Config(cfgfile)
conf = configparser.parse_config()
min_int = conf.getint("analysis", "min_per_int")
export_plot = conf.getboolean("export","plot")
export_csv = conf.getboolean("export","csv")
export_all2csv_link = export_csv
export_all2csv_nw = False

dbinput = Database_input(conf) 

# the new data is in written to conf.links (which contains link-data and lists for records)
dbinput.import_data()
links = dbinput.get_links()

# aggregate data if necessary
if min_int > 15:
    dbinput.aggregate(min_int)

# process and output for each single link ("link-indicators")
for link in links:
    # calculate indicators
    indicatorset = Link_indicatorset(conf.get("analysis", "link_indicators"), link)
    Processor(indicatorset)
    
    # export data
    myoutput = Output_manager(indicatorset, export_plot, export_csv, export_all2csv_link, link)
    myoutput.export_plot()
    myoutput.export_csv()
    
# process and output for the whole linkset ("network-indicators")
indicatorset = Network_indicatorset(conf.get("analysis", "network_indicators"), links)
Processor(indicatorset)
myoutput = Output_manager(indicatorset, export_plot, export_csv, export_all2csv_nw)
myoutput.export_plot()
myoutput.export_csv()

# for developing it is nice to see the plots in the pylab-gui
if export_plot and conf.getboolean("export","show_pylab"):
    pylab.show()

logging.info("Regular end of application")
